package com.objecteffects.template.web.action;

import javax.inject.Inject;
import javax.servlet.http.Cookie;

import com.objecteffects.template.model.UserEntity;
import com.objecteffects.template.service.UserEntityService;
import com.objecteffects.template.web.utils.TemplateCookie;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;

/**
 * @author Rusty Wright
 */
public class UserLogoutActionBean extends BaseActionBean {
    private final transient Logger log = LoggerFactory
        .getLogger(UserLogoutActionBean.class);

    private final UserEntityService userEntityService;
    private final TemplateCookie templateCookie;

    @Inject
    UserLogoutActionBean(final UserEntityService _userEntityService,
        final TemplateCookie _templateCookie) {
        this.userEntityService = _userEntityService;
        this.templateCookie = _templateCookie;
    }

    public Resolution logout() {
        final Cookie cookie =
            this.templateCookie.findCookie(this.getContext().getRequest());

        if (cookie != null) {
            this.log.debug("cookie is not null");

            cookie.setMaxAge(0);

            this.getContext().getResponse().addCookie(cookie);
        }

        final Long userId = this.getContext().getUserId();

        if (userId != null) {
            final UserEntity userEntity =
                this.userEntityService.findById(this.getContext().getUserId());

            if (userEntity != null) {
                userEntity.setHash(null);

                this.log.debug("nulling hash for user: {}",
                               userEntity.getUserName());
            }

            this.userEntityService.update(userEntity);
        }

        this.getContext().logout();

        return new RedirectResolution(UserLoginActionBean.class);
    }
}
